<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
    NButton,
    NDataTable,
    NForm,
    NFormItem,
    NPagination,
    useMessage,
    NDatePicker,
    NSpace,
    NSelect,
    type DataTableColumns
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated, onMounted } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import { RecordType } from '@/router/utils'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
    {
        title: '申请人',
        key: 'userName',
        width: '5rem',
        align: useStore.isCenter
    },
    {
        title: '申请人部门',
        key: 'deptName',
        width: '10rem',
        align: useStore.isCenter
    },
    {
        title: '报销类型',
        key: 'reimburseType',
        width: '10rem',
        align: useStore.isCenter,
        render(e: any) {
            return renderType(e.reimburseType)
        }
    },
    {
        title: '总金额(元)',
        key: 'amount',
        width: '10rem',
        align: useStore.isCenter
    },
    {
        title: '申请日期',
        key: 'submitTime',
        width: '10rem',
        align: useStore.isCenter
    },
    {
        title: '操作',
        key: 'action',
        width: '12rem',
        align: useStore.isCenter,
        fixed: 'right',
        render: (e: any) => [
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    onClick: () => {
                        RecordType.setRouteNameTypeFalse('A0548')
                        handleDetail(e)
                    }
                },
                {
                    default: () => '详情'
                }
            ),
            h(
                NButton,
                {
                    type: 'info',
                    quaternary: true,
                    style: {
                        display: e.fromStatusCode == 'A0605' ? 'inline-flex' : 'none'
                    },
                    onClick: () => handleExport(e)
                },
                {
                    default: () => '导出'
                }
            )
        ]
    }
]
//处理报销类型
const renderType = (val: any) => {
    if (val == '0') {
        return '差旅'
    } else if (val == '1') {
        return '合同'
    } else if (val == '3') {
        return '公出'
    } else if (val == '4') {
        return '接待'
    } else if (val == '5') {
        return '劳务'
    } else {
        return '其他'
    }
}
//部门人员
const partList: any = ref([])
const getPartName = async () => {
    const [error, res] = await sendRequest({
        module: 'office',
        api: 'partPersons',
        override: {
            params: {
                deptId: null
            }
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    partList.value = res.data.map((r: any) => {
        return {
            label: r.name,
            value: r.value
        }
    })
}
//日期选择器
const timeRange: any = ref()
const startTime = ref()
const endTime = ref()
function handleUpdateFormattedValue(e: string[]) {
    if (timeRange.value == null) {
        startTime.value = null
        endTime.value = null
    } else {
        startTime.value = e[0]
        endTime.value = e[1]
    }
}
//筛选条件
const paginationReactive = reactive({
    deptId: null,
    userId: null,
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [10, 20, 50, 100, 500],
    itemCount: 0,
    onChange: (page: number) => {
        paginationReactive.page = page
        queryTableData()
    },
    onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        queryTableData()
    }
})
//详情
const handleDetail = (val: any) => {
    router.push({
        path: '/OA/Account/AccountDetail',
        query: {
            id: val.id
        }
    })
}
//下载
function download(headers: any, data: any, name?: string) {
    const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
    let filename = val ? decodeURIComponent(val[0]) : name + '.xlsx'
    if (!filename.includes('xlsx')) {
        filename = filename.replace('xls', 'xlsx')
    }
    const a = document.createElement('a')
    let binaryData = []
    binaryData.push(data)
    a.href = window.URL.createObjectURL(new Blob(binaryData))
    a.download = filename
    a.click()
    window.URL.revokeObjectURL(a.href)
}
//导出
async function handleExport(val: any) {
    tableLoading.value = true
    const [error, data, headers] = await sendRequest({
        module: 'account',
        api: 'accountExport',
        override: {
            params: {
                id: val.id
            }
        }
    })
    if (error) return message.error(error.message)
    download(headers, data, '报销审批单')
    tableLoading.value = false
}
//导出全部
const exportAllLoading = ref(false)
async function handleExportAll() {
    exportAllLoading.value = true
    const [error, data, headers] = await sendRequest({
        module: 'account',
        api: 'accountDepExport',
        override: {
            params: {
                page: 1,
                limit: 99999
            }
        }
    })
    if (error) return message.error(error.message)
    download(headers, data, '报销审批单')
    exportAllLoading.value = false
}
//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
    if (resetPage) paginationReactive.page = 1
    tableLoading.value = true
    const [error, res] = await sendRequest({
        module: 'account',
        api: 'partaccountList',
        override: {
            params: {
                startTime: startTime.value,
                endTime: endTime.value,
                page: paginationReactive.page,
                limit: paginationReactive.pageSize,
                userId: paginationReactive.userId,
            }
        }
    })
    tableLoading.value = false
    if (error) return message.error(error.message)
    paginationReactive.itemCount = res.data?.totalCount
    const tmp: any = res.data
    tableData.value = tmp?.list
}
//当前月第一天
function getFirstDay() {
    let y: any = new Date().getFullYear(); //获取年份
    let m: any = new Date().getMonth() + 1; //获取月份
    let d: any = "01";
    m = m < 10 ? "0" + m : m; //月份补 0
    return [y, m, d].join("-");
}
//当前月最后一天
function getLastDay() {
    let y: any = new Date().getFullYear(); //获取年份
    let m: any = new Date().getMonth() + 1; //获取月份
    let d: any = new Date(y, m, 0).getDate(); //获取当月最后一日
    m = m < 10 ? "0" + m : m; //月份补 0
    d = d < 10 ? "0" + d : d; //日数补 0
    return [y, m, d].join("-");
}

onMounted(async () => {

})

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1, queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
    () => route,
    async () => {
        if (route.path == '/OA/Account/AccountPart') {
            timeRange.value = [getFirstDay(), getLastDay()]
            startTime.value = timeRange.value[0]
            endTime.value = timeRange.value[1]
            await getPartName()
            await queryTableData()
            window.addEventListener('keyup', keyUpDown, false)
        }
    },
    { deep: true, immediate: true }
)
</script>

<template>
    <TableView class="table">
        <template #form>
            <NSpace justify="space-between">
                <NForm :show-feedback="false" label-placement="left" inline>
                    <NFormItem label="统计日期:">
                        <NDatePicker input-readonly placeholder="请选择日期范围" type="daterange"
                            v-model:formatted-value="timeRange" @update-formatted-value="handleUpdateFormattedValue"
                            clearable />
                    </NFormItem>
                    <NFormItem label="部门人员:">
                        <NSelect :options="partList" v-model:value="paginationReactive.userId" placeholder="请选择部门人员"
                            clearable style="width: 200px" filterable />
                    </NFormItem>
                    <NFormItem>
                        <NButton type="primary" style="width: 78px; margin-right: 40rem" ghost
                            @click="queryTableData(true)">
                            查询
                        </NButton>
                    </NFormItem>
                </NForm>
                <NSpace align="end">
                    <NButton type="primary" style="width: 115px" @click="handleExportAll" :loading="exportAllLoading">
                        导出
                    </NButton>
                </NSpace>
            </NSpace>
        </template>

        <template #table="props">
            <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
                :loading="tableLoading" />
        </template>

        <template #pagination>
            <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
                :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
                @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
                show-size-picker show-quick-jumper :suffix="() => '页'">
                <template #prefix>
                    <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
                </template>
            </NPagination>
        </template>
    </TableView>
</template>

<style scoped lang="scss">
.table {
    height: 100%;
    padding: 29px 30px 42px;
}
</style>
